package com.mapapp.flutter_mapapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ServiceUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.Utils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mapapp.flutter_mapapp.R;
import com.mapapp.flutter_mapapp.adapter.AddPictureAdapter;
import com.mapapp.flutter_mapapp.adapter.NewDataStepAdapter;
import com.mapapp.flutter_mapapp.application.Constants;
import com.mapapp.flutter_mapapp.application.MyApplication;
import com.mapapp.flutter_mapapp.bean.HomePageShouldBeRefreshed;
import com.mapapp.flutter_mapapp.bean.LogEntity;
import com.mapapp.flutter_mapapp.bean.NewDataProcessBean;
import com.mapapp.flutter_mapapp.bean.ProcessBean;
import com.mapapp.flutter_mapapp.bean.WaitForUploading;
import com.mapapp.flutter_mapapp.bean.WaitForUploadingDao;
import com.mapapp.flutter_mapapp.http.Url;
import com.mapapp.flutter_mapapp.persenter.NewDataPresenter;
import com.mapapp.flutter_mapapp.service.AudioRecordService;
import com.mapapp.flutter_mapapp.util.FTPClientFunctions;
import com.mapapp.flutter_mapapp.util.GlideApp;
import com.mapapp.flutter_mapapp.util.HorizontalSpaceItemDecoration;
import com.mapapp.flutter_mapapp.util.RxBus;
import com.mapapp.flutter_mapapp.util.SelectPhotoUtil;
import com.mapapp.flutter_mapapp.util.SharePreferenceUtil;
import com.mapapp.flutter_mapapp.util.SortableUUID;
import com.mapapp.flutter_mapapp.util.ToastUtils;
import com.mapapp.flutter_mapapp.view.NewDataViewInterface;
import com.mapapp.flutter_mapapp.widget.BackDialog;
import com.mapapp.flutter_mapapp.widget.CacheWarnDialog;
import com.mapapp.flutter_mapapp.widget.ErrorCorrectionPopWindow;
import com.mapapp.flutter_mapapp.widget.ReplaceCacheDialog;
import com.mapapp.flutter_mapapp.widget.TitleBar;
import com.mapapp.flutter_mapapp.widget.UploadDataConfirmDialog;
import com.mapapp.flutter_mapapp.widget.UploadDataProgressDialog;
import com.zhihu.matisse.Matisse;

import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NewDataActivity extends ImmersiveBaseActivity implements NewDataViewInterface {

    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.iv_door_photo)
    ImageView ivDoorPhoto;
    @BindView(R.id.step_options)
    TextView stepOptions;
    @BindView(R.id.rv_step)
    RecyclerView rvStep;
    @BindView(R.id.tv_add_remark)
    TextView tvAddRemark;
    @BindView(R.id.et_add_remark)
    EditText etAddRemark;
    @BindView(R.id.tv_add_pictures)
    TextView tvAddPictures;
    @BindView(R.id.rv_add_pictures)
    RecyclerView rvAddPictures;
    @BindView(R.id.tv_error_correction)
    TextView tvErrorCorrection;
    @BindView(R.id.tv_end)
    TextView tvEnd;
    @BindView(R.id.anchor)
    View anchor;
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.cv_error_correction)
    CardView cvErrorCorrection;

    private AddPictureAdapter pictureAdapter;
    private FTPClientFunctions ftpClientTool;
    ArrayList<String> mSelected = new ArrayList<>();
    private static final int REQUEST_CODE_CHOOSE = 1991;
    private static final int REQUEST_CODE_DOOR = 1992;

    private ProcessBean currentProcessBean;
    private int currentProcess;
    private int totalProcess;

    private File headPhotoFile;

    private NewDataStepAdapter stepAdapter;

    private NewDataPresenter presenter;

    private boolean allHaveBeenCompleted = true;

    private UploadDataConfirmDialog dataConfirmDialog;

    private String regionId;
    private String address;
    private int type;

    private UploadDataProgressDialog uploadDataProgressDialog;

    private String dirName = SortableUUID.randomUUID();

    WaitForUploading unique;

    private String audioDirName = SortableUUID.randomUUID();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_data);

        regionId = getIntent().getStringExtra("regionId");
        address = getIntent().getStringExtra("address");
        type = getIntent().getIntExtra("type", 0);

        presenter = new NewDataPresenter(this, this, lifecycleSubject);

        ButterKnife.bind(this);

        rvAddPictures.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        rvAddPictures.setNestedScrollingEnabled(false);
        pictureAdapter = new AddPictureAdapter(R.layout.item_add_picture);
        View headerView = LayoutInflater.from(mContext).inflate(R.layout.header_add_picture, rvAddPictures, false);
        pictureAdapter.setHeaderView(headerView, 0, LinearLayout.HORIZONTAL);
        rvAddPictures.setAdapter(pictureAdapter);
        rvAddPictures.addItemDecoration(new HorizontalSpaceItemDecoration(SizeUtils.dp2px(2)));
        headerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tvStart.isSelected()) {
                    ToastUtils.showMessage(mContext, "请先点击开始按钮");
                    return;
                }
                if (NetworkUtils.isConnected()) {
                    presenter.submitOperateInfo("1", regionId, null, null);
                } else {
                    LogEntity logEntity = new LogEntity();
                    logEntity.setCurrentMills(System.currentTimeMillis());
                    logEntity.setRegionId(regionId);
                    logEntity.setType("3");
                    MyApplication.getInstance().getDaoSession().getLogEntityDao().insert(logEntity);
                }

                SelectPhotoUtil.openPhotoAlbum(NewDataActivity.this, REQUEST_CODE_CHOOSE);
            }
        });

        pictureAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                pictureAdapter.remove(position);
                mSelected.remove(position);
            }
        });

        pictureAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(mContext, PreviewPictureActivity.class);
                intent.putStringArrayListExtra("images", mSelected);
                intent.putExtra("current", position + 1);
                startActivity(intent);
            }
        });


        rvStep.setLayoutManager(new LinearLayoutManager(mContext));
        stepAdapter = new NewDataStepAdapter(R.layout.item_step_new_data, null);
        rvStep.setAdapter(stepAdapter);
        stepAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                for (ProcessBean datum : stepAdapter.getData()) {
                    datum.setSelected(false);
                }
                stepAdapter.getData().get(position).setSelected(true);
                currentProcessBean = stepAdapter.getData().get(position);
                currentProcess = position + 1;
                stepAdapter.notifyDataSetChanged();
            }
        });

        if (type == 1 || type == 2) {
            stepAdapter.setShowRadioBtn(true);
        }
        titleBar.getIvBack().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });


        unique = MyApplication.getInstance().getDaoSession().getWaitForUploadingDao()
                .queryBuilder().where(WaitForUploadingDao.Properties.RegionId.eq(regionId),
                        WaitForUploadingDao.Properties.HostAddress.eq(Url.BASE_URL),
                        WaitForUploadingDao.Properties.UserId.eq(SharePreferenceUtil.get(mContext, Constants.USERNAME, ""))).unique();
        if (unique != null) {
            CacheWarnDialog cacheWarnDialog = new CacheWarnDialog(mContext);
            cacheWarnDialog.setOutSideDismiss(false);
            cacheWarnDialog.showPopupWindow();
            cacheWarnDialog.setListener(new CacheWarnDialog.OnItemClickListener() {
                @Override
                public void onClickUploading() {
                    finish();
                    startActivity(new Intent(mContext, UploadDataActivity.class));
                }

                @Override
                public void onClickContinue() {
                    if (unique.getCategory() == 1 || unique.getCategory() == 2) {
                        return;
                    }
                    String photosPath = unique.getPhotosPath();
                    String headPicPath = unique.getHeadPicPath();
                    String remark = unique.getRemark();

                    if (photosPath != null) {
                        String[] pathList = photosPath.split(",");
                        if (pathList.length > 0) {
                            List<String> list = Arrays.asList(pathList);
                            mSelected.addAll(list);
                            pictureAdapter.setNewData(mSelected);
                        }
                    }

                    File file = new File(headPicPath);
                    if (file.exists()) {
                        headPhotoFile = file;
                    }

                    etAddRemark.setText(remark);
                    GlideApp.with(mContext).load(headPicPath).into(ivDoorPhoto);

                    audioDirName = unique.getAudioDirName();
                    dirName = unique.getPhotoDirName();

                    tvStart.setSelected(true);
                    tvStart.setVisibility(View.INVISIBLE);
                    ServiceUtils.startService(AudioRecordService.class);
                }
            });
        }

        presenter.showProcess(regionId, type);

    }

    @Override
    protected void onResume() {
        super.onResume();
        unique = MyApplication.getInstance().getDaoSession().getWaitForUploadingDao()
                .queryBuilder().where(WaitForUploadingDao.Properties.RegionId.eq(regionId),
                        WaitForUploadingDao.Properties.HostAddress.eq(Url.BASE_URL),
                        WaitForUploadingDao.Properties.UserId.eq(SharePreferenceUtil.get(mContext, Constants.USERNAME, ""))).unique();
    }

    private synchronized void upload(final List<String> pathList, final List<String> nameList, final String dirName,
                                     final List<String> audioNames, final String audioDir,
                                     final List<String> childPathList, final List<String> childNameList,
                                     final String childPhotoDir, final WaitForUploading datum) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (ftpClientTool == null) {
                    ftpClientTool = new FTPClientFunctions();
                }

                boolean connectResult = ftpClientTool.ftpConnect(Url.getInstance().ftpServer, Url.getInstance().ftpUsername, Url.getInstance().ftpPassword, Url.getInstance().ftpPort);
                if (connectResult) {
                    final FTPClient ftpClient = ftpClientTool.getFtpClient();
                    try {
                        if (audioNames != null) {
                            ftpClient.changeWorkingDirectory("/radio");
                            ftpClient.makeDirectory(datum.getAudioDirName());
                            boolean radioDir = ftpClient.changeWorkingDirectory("/radio/" + datum.getAudioDirName());

                            if (radioDir) {
                                boolean b = true;
                                for (String audioName : audioNames) {
                                    b = ftpClientTool.ftpUpload(AudioRecordService.FILE_DIR, audioName);
                                    if (!b) {
                                        break;
                                    }
                                }
                                if (b) {
                                    ftpClientTool.ftpUploadList(dirName, pathList, nameList, childPhotoDir, childPathList, childNameList);
                                } else {
                                    showUploadFailed(2);
                                }
                            } else {
                                showUploadFailed(2);
                            }
                        } else {
                            ftpClientTool.ftpUploadList(dirName, pathList, nameList, childPhotoDir, childPathList, childNameList);
                        }
                    } catch (IOException e) {
                        showUploadFailed(2);
                        e.printStackTrace();
                    }
                } else {
                    showUploadFailed(0);
                }

            }
        }).start();

    }

    @Override
    public void onBackPressed() {
        if (allHaveBeenCompleted) {
            super.onBackPressed();
        } else {
            BackDialog backDialog = new BackDialog(mContext);
            backDialog.showPopupWindow();
            backDialog.setListener(new BackDialog.OnItemEnsureClickListener() {
                @Override
                public void onClick() {
//                    if (AudioRecordService.getIsServerRun()) {
//                        String dir = AudioRecordService.FILE_DIR;
//                        String name = AudioRecordService.audioName;
//                        ServiceUtils.stopService(AudioRecordService.class);
//                        File audio = new File(dir, name);
//                        if (audio.exists()) {
//                            audio.delete();
//                        }
//                    }
                    finish();
                }
            });
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_CHOOSE) {
                if (Matisse.obtainPathResult(data) != null) {
                    mSelected.addAll(Matisse.obtainPathResult(data));
                }
                pictureAdapter.setNewData(mSelected);
            } else if (REQUEST_CODE_DOOR == requestCode) {
                List<String> pathResult = Matisse.obtainPathResult(data);
                if (pathResult != null && !pathResult.isEmpty()) {
                    headPhotoFile = new File(pathResult.get(0));
                    GlideApp.with(mContext).load(headPhotoFile).into(ivDoorPhoto);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ServiceUtils.stopService(AudioRecordService.class);
    }

    @OnClick({R.id.tv_start, R.id.tv_error_correction, R.id.tv_end, R.id.title_bar_right, R.id.iv_door_photo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_door_photo:
                if (!tvStart.isSelected()) {
                    ToastUtils.showMessage(mContext, "请先点击开始按钮");
                    return;
                }
                if (NetworkUtils.isConnected()) {
                    presenter.submitOperateInfo("1", regionId, null, null);
                } else {
                    LogEntity logEntity = new LogEntity();
                    logEntity.setCurrentMills(System.currentTimeMillis());
                    logEntity.setRegionId(regionId);
                    logEntity.setType("3");
                    MyApplication.getInstance().getDaoSession().getLogEntityDao().insert(logEntity);
                }

                SelectPhotoUtil.openPhotoAlbum(NewDataActivity.this, REQUEST_CODE_DOOR, 1);
                break;
            case R.id.title_bar_right:
                Intent intent = new Intent(mContext, HistoryActivity.class);
                intent.putExtra("regionId", regionId);
                intent.putExtra("householdName", titleBar.getTitleBarCenter().getText().toString());
                startActivity(intent);
                break;
            case R.id.tv_start:
                if (currentProcessBean == null) {
                    switch (type) {
                        case 0:
                            ToastUtils.showMessage(mContext, "正在获取步骤数据");
                            break;
                        case 1:
                            ToastUtils.showMessage(mContext, "请选择要修改的步骤");
                            break;
                        case 2:
                            ToastUtils.showMessage(mContext, "请选择要覆盖的步骤");
                            break;
                    }
                    return;
                }

                if (allHaveBeenCompleted) {
                    ToastUtils.showMessage(mContext, "所有步骤已全部完成");
                    break;
                }

                if (tvStart.isSelected()) {
                    return;
                }
                if (NetworkUtils.isConnected()) {
                    presenter.submitOperateInfo("0", regionId, currentProcessBean.getId(), null);
                } else {
                    LogEntity logEntity = new LogEntity();
                    logEntity.setCurrentMills(System.currentTimeMillis());
                    logEntity.setRegionId(regionId);
                    logEntity.setProcessId(currentProcessBean.getId());
                    logEntity.setType("0");
                    MyApplication.getInstance().getDaoSession().getLogEntityDao().insert(logEntity);
                }

                tvStart.setSelected(true);
                tvStart.setVisibility(View.INVISIBLE);
                ServiceUtils.startService(AudioRecordService.class);

                SelectPhotoUtil.openPhotoAlbum(NewDataActivity.this, REQUEST_CODE_DOOR, 1);

                break;
            case R.id.tv_error_correction:
                if (!tvStart.isSelected()) {
                    ToastUtils.showMessage(mContext, "请先点击开始按钮");
                    return;
                }

                ErrorCorrectionPopWindow errorCorrectionPopWindow = new ErrorCorrectionPopWindow(this);
                errorCorrectionPopWindow.setPopupGravity(Gravity.TOP);
                errorCorrectionPopWindow.setBackground(0);
                errorCorrectionPopWindow.showPopupWindow(anchor);
                errorCorrectionPopWindow.setListener(new ErrorCorrectionPopWindow.OnItemClickListener() {
                    Intent intent = new Intent();

                    @Override
                    public void onClick(int index) {
                        switch (index) {
                            case 0:  //合户
                                if (unique == null) {
                                    intent.putExtra("regionId", NewDataActivity.this.regionId);
                                    intent.putExtra("audioDir", audioDirName);
                                    intent.setClass(mContext, MergeHouseholdActivity.class);
                                    intent.putExtra("address", NewDataActivity.this.address);
                                    startActivity(intent);
                                } else {
                                    if (unique.getCategory() == 1 || unique.getCategory() == 3) {
                                        ReplaceCacheDialog replaceCacheDialog = new ReplaceCacheDialog(mContext, true);
                                        replaceCacheDialog.showPopupWindow();
                                        replaceCacheDialog.setListener(new ReplaceCacheDialog.OnItemEnsureClickListener() {
                                            @Override
                                            public void onClick() {
                                                intent.putExtra("regionId", NewDataActivity.this.regionId);
                                                intent.putExtra("audioDir", audioDirName);
                                                intent.setClass(mContext, MergeHouseholdActivity.class);
                                                intent.putExtra("address", NewDataActivity.this.address);
                                                startActivity(intent);
                                            }
                                        });
                                    } else {
                                        intent.putExtra("regionId", NewDataActivity.this.regionId);
                                        intent.putExtra("audioDir", audioDirName);
                                        intent.setClass(mContext, MergeHouseholdActivity.class);
                                        intent.putExtra("address", NewDataActivity.this.address);
                                        startActivity(intent);
                                    }
                                }

                                break;
                            case 1:   //分户
                                if (unique == null) {
                                    intent.putExtra("regionId", NewDataActivity.this.regionId);
                                    intent.setClass(mContext, SeparateHouseholdsActivity.class);
                                    intent.putExtra("address", NewDataActivity.this.address);
                                    intent.putExtra("audioDir", audioDirName);
                                    startActivity(intent);
                                } else {
                                    if (unique.getCategory() == 2 || unique.getCategory() == 4) {
                                        ReplaceCacheDialog replaceCacheDialog = new ReplaceCacheDialog(mContext, false);
                                        replaceCacheDialog.showPopupWindow();
                                        replaceCacheDialog.setListener(new ReplaceCacheDialog.OnItemEnsureClickListener() {
                                            @Override
                                            public void onClick() {
                                                intent.putExtra("regionId", NewDataActivity.this.regionId);
                                                intent.setClass(mContext, SeparateHouseholdsActivity.class);
                                                intent.putExtra("address", NewDataActivity.this.address);
                                                intent.putExtra("audioDir", audioDirName);
                                                startActivity(intent);
                                            }
                                        });
                                    } else {
                                        intent.putExtra("regionId", NewDataActivity.this.regionId);
                                        intent.setClass(mContext, SeparateHouseholdsActivity.class);
                                        intent.putExtra("address", NewDataActivity.this.address);
                                        intent.putExtra("audioDir", audioDirName);
                                        startActivity(intent);
                                    }
                                }

                                break;
                            case 2:   //其他
                                intent.putExtra("regionId", NewDataActivity.this.regionId);
                                intent.setClass(mContext, OtherInfoActivity.class);
                                startActivity(intent);
                                break;
                        }
                    }
                });
                break;
            case R.id.tv_end:
                if (!tvStart.isSelected()) {
                    ToastUtils.showMessage(mContext, "请先点击开始按钮");
                    return;
                }

                if (headPhotoFile == null || !headPhotoFile.exists()) {
                    ToastUtils.showMessage(mContext, "请拍摄门头照");
                    return;
                }

                if (currentProcessBean == null) {
                    switch (type) {
                        case 0:
                            ToastUtils.showMessage(mContext, "正在获取步骤数据");
                            break;
                        case 1:
                            ToastUtils.showMessage(mContext, "请选择要修改的步骤");
                            break;
                        case 2:
                            ToastUtils.showMessage(mContext, "请选择要覆盖的步骤");
                            break;
                    }
                    return;
                }

                ServiceUtils.stopService(AudioRecordService.class);

                if (dataConfirmDialog == null) {
                    dataConfirmDialog = new UploadDataConfirmDialog(mContext);
                }

                dataConfirmDialog.showPopupWindow();

                final String remark = etAddRemark.getText().toString();
                final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                final String endTime = dateFormat.format(new Date(System.currentTimeMillis()));

                final WaitForUploading waitForUploading;
                if (unique != null) {
                    waitForUploading = unique;
                    if (!TextUtils.isEmpty(waitForUploading.getAudioName()) &&
                            !waitForUploading.getAudioName().contains(AudioRecordService.audioName)) {
                        waitForUploading.setAudioName(waitForUploading.getAudioName() + "," + AudioRecordService.audioName);
                    }
                    int category = waitForUploading.getCategory();
                    switch (category) {
                        case 0:
                            waitForUploading.setCategory(0);
                            break;
                        case 1:
                        case 3:
                            waitForUploading.setCategory(3);
                            break;
                        case 2:
                        case 4:
                            waitForUploading.setCategory(4);
                            break;
                    }
                } else {
                    waitForUploading = new WaitForUploading();
                    waitForUploading.setAudioName(AudioRecordService.audioName);
                    waitForUploading.setAudioPath(AudioRecordService.FILE_DIR);
                    waitForUploading.setCategory(0);
                }

                waitForUploading.setEndTime(endTime);
                waitForUploading.setHostAddress(Url.BASE_URL);

                waitForUploading.setProcessStartTime(currentProcessBean.getCreateTime());
                waitForUploading.setPhotoDirName(dirName);
                waitForUploading.setAudioDirName(audioDirName);
                waitForUploading.setUserId((String) SharePreferenceUtil.get(mContext, Constants.USERNAME, ""));

                final List<String> pathListTemp = new ArrayList<>();
                final List<String> nameListTemp = new ArrayList<>();
                for (String s : mSelected) {
                    pathListTemp.add(s);
                    String uuid = SortableUUID.randomUUID();
                    nameListTemp.add(uuid + ".jpg");
                }

                if (headPhotoFile != null && headPhotoFile.exists()) {
                    waitForUploading.setHeadPicPath(headPhotoFile.getAbsolutePath());
                    waitForUploading.setHeadPicName("top_" + SortableUUID.randomUUID() + ".jpg");
                }

                if (!nameListTemp.isEmpty()) {
                    StringBuilder nameBuilder = new StringBuilder();
                    StringBuilder pathBuilder = new StringBuilder();
                    for (String s : nameListTemp) {
                        nameBuilder.append(s).append(",");
                    }
                    for (String s : pathListTemp) {
                        pathBuilder.append(s).append(",");
                    }
                    nameBuilder.deleteCharAt(nameBuilder.length() - 1);
                    pathBuilder.deleteCharAt(pathBuilder.length() - 1);
                    waitForUploading.setPhotosName(nameBuilder.toString());
                    waitForUploading.setPhotosPath(pathBuilder.toString());
                }

                waitForUploading.setProcessId(currentProcessBean.getId());
                waitForUploading.setRegionId(regionId);

                waitForUploading.setType(type);
                waitForUploading.setAddress(address + " (" + currentProcess + "/" + totalProcess + ")");
                waitForUploading.setRemark(remark);

                dataConfirmDialog.setListener(new UploadDataConfirmDialog.OnItemClickListener() {
                    @Override
                    public void onClickSubmit(final int state) {
                        waitForUploading.setState(state);
                        String photosPath = waitForUploading.getPhotosPath();
                        String photosName = waitForUploading.getPhotosName();
                        String audioName = waitForUploading.getAudioName();
                        String childPhotosName = waitForUploading.getChildPhotosName();
                        String childPhotosPath = waitForUploading.getChildPhotosPath();
                        final List<String> pathList;
                        final List<String> nameList;
                        final List<String> audioList;
                        final List<String> childPathList;
                        final List<String> childNameList;
                        if (!TextUtils.isEmpty(photosPath) && !TextUtils.isEmpty(photosName)) {
                            pathList = new ArrayList<>(Arrays.asList(photosPath.split(",")));
                            nameList = new ArrayList<>(Arrays.asList(photosName.split(",")));
                            pathList.add(waitForUploading.getHeadPicPath());
                            nameList.add(waitForUploading.getHeadPicName());
                        } else {
                            if (waitForUploading.getHeadPicPath() != null) {
                                pathList = new ArrayList<>();
                                nameList = new ArrayList<>();
                                pathList.add(waitForUploading.getHeadPicPath());
                                nameList.add(waitForUploading.getHeadPicName());
                            } else {
                                pathList = null;
                                nameList = null;
                            }
                        }
                        if (audioName != null) {
                            audioList = Arrays.asList(audioName.split(","));
                        } else {
                            audioList = null;
                        }

                        if (!TextUtils.isEmpty(childPhotosName) && !TextUtils.isEmpty(childPhotosPath)) {
                            childPathList = Arrays.asList(childPhotosPath.split(","));
                            childNameList = Arrays.asList(childPhotosName.split(","));
                        } else {
                            childPathList = null;
                            childNameList = null;
                        }

                        upload(pathList, nameList, waitForUploading.getPhotoDirName(), audioList,
                                waitForUploading.getAudioDirName(), childPathList, childNameList,
                                waitForUploading.getChildPhotoDirName(), waitForUploading);

                        uploadDataProgressDialog = new UploadDataProgressDialog(mContext);
                        uploadDataProgressDialog.showPopupWindow();

                        ftpClientTool.setListener(new FTPClientFunctions.OnUploadPositionListener() {
                            @Override
                            public void onProgress(final int position, final int total) {
                                Utils.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadDataProgressDialog.setProgress(position, total);
                                    }
                                });
                            }

                            @Override
                            public void onSuccess() {
                                Utils.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadDataProgressDialog.dismiss();
                                        ftpClientTool.ftpDisconnect();
                                        doGet(waitForUploading);
                                    }
                                });
                            }

                            @Override
                            public void onFailed() {
                                try {
                                    if (nameList != null) {
                                        ftpClientTool.getFtpClient().changeToParentDirectory();
                                        boolean b = ftpClientTool.getFtpClient().changeWorkingDirectory("/" + waitForUploading.getPhotoDirName());
                                        if (b) {
                                            for (String s : nameList) {
                                                ftpClientTool.getFtpClient().deleteFile(s);
                                            }
                                        }
                                    }

                                    if (childNameList != null) {
                                        ftpClientTool.getFtpClient().changeToParentDirectory();
                                        boolean b = ftpClientTool.getFtpClient().changeWorkingDirectory("/" + waitForUploading.getChildPhotoDirName());
                                        if (b) {
                                            for (String s : childNameList) {
                                                ftpClientTool.getFtpClient().deleteFile(s);
                                            }
                                        }
                                    }

                                    if (audioList != null) {
                                        ftpClientTool.getFtpClient().changeToParentDirectory();
                                        ftpClientTool.getFtpClient().changeWorkingDirectory("/radio");
                                        boolean b = ftpClientTool.getFtpClient().changeWorkingDirectory("/radio/" + waitForUploading.getAudioDirName());
                                        if (b) {
                                            for (String s : audioList) {
                                                ftpClientTool.getFtpClient().deleteFile(s);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                ftpClientTool.ftpDisconnect();
                                Utils.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadDataProgressDialog.dismiss();
                                        //上传失败后清理已上传文件

                                        ToastUtils.showMessage(mContext, "上传失败");
                                    }
                                });
                            }
                        });

                    }

                    @Override
                    public void onClickSave(int state) {
                        if (NetworkUtils.isConnected()) {
                            presenter.submitOperateInfo("1", waitForUploading.getRegionId(), waitForUploading.getProcessId(), null);
                        } else {
                            LogEntity logEntity = new LogEntity();
                            logEntity.setCurrentMills(System.currentTimeMillis());
                            logEntity.setProcessId(waitForUploading.getProcessId());
                            logEntity.setRegionId(waitForUploading.getRegionId());
                            logEntity.setType("1");
                            MyApplication.getInstance().getDaoSession().getLogEntityDao().insert(logEntity);
                        }

                        waitForUploading.setState(state);
                        WaitForUploadingDao waitForUploadingDao = MyApplication.getInstance().getDaoSession().getWaitForUploadingDao();
                        waitForUploadingDao.insertOrReplace(waitForUploading);
                        ToastUtils.showMessage(mContext, "保存成功");
                        RxBus.get().post("refresh", new HomePageShouldBeRefreshed());
                        finish();
                    }
                });
                break;
        }

    }


    private void doGet(WaitForUploading datum) {
        switch (datum.getCategory()) {
            case 0:
                presenter.submitProcess(datum.getRemark(), datum.getEndTime(), datum.getPhotoDirName(), datum.getProcessId(),
                        datum.getAudioDirName(), datum.getRegionId(), datum.getProcessStartTime(), datum.getState(), datum.getType());
                break;
            case 1:
                presenter.submitSplitRegionNoDialog(datum.getRegionId(), datum.getSeparationHouseholdCount(), datum.getChildRemark(), datum.getAudioDirName(), datum.getChildPhotoDirName());
                break;
            case 2:
                presenter.submitMergeRegionNoDialog(datum.getRegionId(), datum.getMergedIds(), datum.getChildRemark(), datum.getAudioDirName(), datum.getChildPhotoDirName());
                break;
            case 3:
                presenter.submitProcess(datum.getRemark(), datum.getEndTime(), datum.getPhotoDirName(), datum.getProcessId(),
                        datum.getAudioDirName(), datum.getRegionId(), datum.getProcessStartTime(), datum.getState(), datum.getType());

                presenter.submitSplitRegionNoDialog(datum.getRegionId(), datum.getSeparationHouseholdCount(), datum.getChildRemark(), datum.getAudioDirName(), datum.getChildPhotoDirName());
                break;
            case 4:
                presenter.submitProcess(datum.getRemark(), datum.getEndTime(), datum.getPhotoDirName(), datum.getProcessId(),
                        datum.getAudioDirName(), datum.getRegionId(), datum.getProcessStartTime(), datum.getState(), datum.getType());
                presenter.submitMergeRegionNoDialog(datum.getRegionId(), datum.getMergedIds(), datum.getChildRemark(), datum.getAudioDirName(), datum.getChildPhotoDirName());
                break;
        }
    }

//    private void openCamera() {
//        preHeadPhotoFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
//                "top_" + SortableUUID.randomUUID() + ".jpg");
//        Uri uri;
//        //判断是否是AndroidN以及更高的版本
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            uri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileProvider", preHeadPhotoFile);
//        } else {
//            uri = Uri.fromFile(preHeadPhotoFile);
//        }
//        startActivityForResult(IntentUtils.getCaptureIntent(uri), CAPTURE_INTENT);
//    }

    @Override
    public void showProcess(NewDataProcessBean processBeanList) {
        if (processBeanList != null) {
            titleBar.getTitleBarCenter().setText(processBeanList.getHouseHoldName());
            List<ProcessBean> processData = processBeanList.getProcessData();
            if (processData != null) {
                totalProcess = processData.size();
                //type == 0是新增，此时将currentProcessBean初始化
                if (type == 0) {
                    for (int i = 0; i < processData.size(); i++) {
                        ProcessBean processBean = processData.get(i);

                        if (processBean.getState() != 1) {
                            allHaveBeenCompleted = false;
                        }

                        // 2是进行中的
                        if (processBean.getState() == 2) {
                            currentProcessBean = processBean;
                            currentProcess = i + 1;
                            break;
                        }
                    }
                }
                stepAdapter.setNewData(processData);
            }
        }

    }

    private void showUploadFailed(final int state) {
        Utils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ftpClientTool.ftpDisconnect();
                if (uploadDataProgressDialog != null) {
                    uploadDataProgressDialog.dismiss();
                }
                switch (state) {
                    case 0:
                        ToastUtils.showMessage(mContext, "连接文件服务器失败");
                        break;
                    case 1:
                        ToastUtils.showMessage(mContext, "本地照片或录音丢失");
                        break;
                    case 2:
                        ToastUtils.showMessage(mContext, "上传文件失败");
                        break;
                }
            }
        });
    }

    @Override
    public void submitProcessStatus(boolean status, String regionId) {
        ftpClientTool.ftpDisconnect();
        if (status) {
            if (unique != null) {
                MyApplication.getInstance().getDaoSession().getWaitForUploadingDao().delete(unique);
            }
            ToastUtils.showMessage(mContext, "成功");
            RxBus.get().post("refresh", new HomePageShouldBeRefreshed());
            finish();
        }
    }
}
